import {Request} from "../../utils/request";
import host from "../../utils/host";
import func from "../../utils/functions";
import map from "../../utils/qqmap-wx-jssdk";
const HostUrl = host.service;
const Requ = new Request();
const Func = new func();
const Map = new map({
    key: 'KE4BZ-POLWP-XAHDB-LCLHX-IML6V-E6B7R'
});
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navH: 0, //页面高度
    choose_send: '1', //配送方式状态
    ShopList: [ //商品列表
      {
        shopimg: '',
        shopname: '五香茶叶蛋',
        shopremarks: '',
        shopnumber: '2',
        shopprice: '4.5'
      },
      {
        shopimg: '',
        shopname: '五香茶叶蛋',
        shopremarks: '热',
        shopnumber: '2',
        shopprice: '4.5'
      },
      {
        shopimg: '',
        shopname: '五香茶叶蛋',
        shopremarks: '',
        shopnumber: '2',
        shopprice: '4.5'
      }
    ],
	isShowShopCar:false,
	distanceShow:"visibility:hidden;",
	latitude:'',
	longitude:'',
	totalPrice:0.00,
	address:{},
	self_site:{}
  },
  // 返回上一层
  goHome: function (e) {
    wx.navigateBack({
      delta: 1,
    })
  },
  //配送方式切换
  ChooseSend: function (e) {
    this.setData({
      choose_send: e.currentTarget.dataset.id
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: async function (options) {
	  let _this = this
	  wx.getStorage({
		  'key':'szx',
		  success(res){
			  res.data = JSON.parse(res.data)
			  console.log(res.data)
			  res.data.juli = Number(res.data.juli)
			  res.data.juli = res.data.juli.toFixed(2)
			  _this.setData({
				  self_site:res.data
			  })
		  }
	  })
	  if(app.globalData.changeAddressFlag){
		  // 获取用户地址
		  new Request('get_user_addresslist.cls.php').request(
		      () => {
		        return {
		          data: 1,
		          openid: app.globalData.openid,
		        }
		      },
		      (res) => {
		  		console.log(res)
		          if(res.data.address == undefined){
		              Requ.showToast('暂无地址信息');
		              return;
		          }
		          this.setData({
		              address: res.data.address
		          })
		      }
		  );
	  }
	  this.GetShopCarList()
	  /* wx.setStorage({
		  'key':"shopCart",
		  'data':app.globalData.shopCart
	  }) */
	  /* app.globalData.shopCart = wx.getStorageSync('shopCart') */
	  console.log(app.globalData.shopCart)
	  this.setData({
	  		  shopCart:app.globalData.shopCart
	  })
	  let length = this.data.shopCart.length
	  if(length == 0){
		  this.setData({
			  isShowShopCar:false
		  })
	  }else{
		  let price = 0.00
		  for(let i=0;i<length;i++){
		  	price+=Number(this.data.shopCart[i].addprice)
		  }
		  price = price.toFixed(2)
		  this.setData({
			  totalPrice:price,
			  isShowShopCar:true
		  })
	  }
	  /* console.log(options)
    this.orderid = options.orderid; */
	/* console.log(app.globalData.self_site_list)
	length = app.globalData.self_site_list.length
	for(let i =0;i<length;i++){
		if(app.globalData.self_site_list[i].id == app.globalData.self_site_id){
			this.setData({
				self_site_name:app.globalData.self_site_list[i].name,
				self_site_address:app.globalData.self_site_list[i].address,
				self_site_latitude:app.globalData.self_site_list[i].latitude,
				self_site_longitude:app.globalData.self_site_list[i].longitude
			})
		}
	} */
	/* this.orderid = getApp().globalData.orderid */
	/* this.orderid = "2016956" */
    var that = this;
	const res = await wx.getLocation({type:'gcj02'})
	that.data.latitude = res.latitude
	that.data.longitude = res.longitude
	this.data.distance = this.getaddreskm(that.data.latitude,that.data.longitude,this.data.self_site_latitude,this.data.self_site_longitude)
	this.data.distance = this.data.distance.toFixed(2)
	that.setData({
      navH: app.globalData.navHeight,
	  distance:that.data.distance
    });
    // 支付订单详情
    /* new Request('3.php').request(
      () => {
        return {
          // order_id: this.orderid,
          order_id: this.orderid,
          openid: app.globalData.openid,
        }
      },
      (res) => {
		  console.log(res.data)
		  if(res.data.code != 1){
			  this.setData({
				  isShowShopCar:false
			  })
			  return
		  }
        let respone = res.data;
        // console.log(respone);
        this.shopcar = respone.shopcar; // 购物车列表
        // 用户信息
        let userInfo = {
          address: respone['address'],
          name: respone['name'],
          phone: respone['phone'],
        };
        // 店铺信息
        let shopInfo = {
          shopName: respone['shopname'],
          sendprice: respone['sendprice'],
        };
        // 支付详情
        let PayInfo = {
          totalprice: parseFloat(respone['totalprice']).toFixed(2),
          discount: parseFloat(respone['discount']).toFixed(2),
        };
        this.setData({
          shopcar: this.shopcar,
          userInfo: userInfo,
          shopInfo: shopInfo,
          PayInfo: PayInfo,
		  isShowShopCar:true,
		  distanceShow:''
        });
      }); */
  },
  // 确认支付
  OnPay: function(){
    new Request('pay_order.cls.php').request(
      () => {
          return {
              order_id: app.globalData.orderid,
              text: '',
              openid: app.globalData.openid,
          }
      },
      (res) => {
		  console.log(res)
          if(res.data.code == 2){
              Requ.showToast(res.data.msg, 'error');
              return;
          }
          wx.requestPayment({
              'timeStamp': res.data.timeStamp.toString(),
              'nonceStr': res.data.nonceStr,
              'package': res.data.package,
              'signType': 'MD5',
              'paySign': res.data.sign,
              'success': function (res) {
				  this.setData({
				    shopcar: [],
				    userInfo: {},
				    shopInfo: {},
				    PayInfo: {},
				    isShowShopCar:false
				  });
                  wx.redirectTo({
                      url: '/pages/order_details/order_details?orderid=' + orderid
                  })
              },
              'fail': function (res) {
                  wx.hideToast()
                  wx.showToast({
                      title: '支付已取消',
                      icon: 'none',
                      duration: 2000
                  })
              }
          })
      });
  },
  // 填写地址
  goselect: function (e) {
    let UserInfo = new Object();
    let address = Object;
	let _this = this
    Func.GetAddress(UserInfo, (res, data) => {
      this.setData({
        UserInfo: data,
      });
      address = {
        address0: "2",
        phone0: data['telNumber'],
        name0: data['userName'],
        addname0: data['detailInfo'],
        AddressDetail: data['provinceName'] + data['cityName'] + data['countyName'] + data['detailInfo'],
      };

      let PromiseId = new Promise((resolve, reject) => {
        // console.log(address.AddressDetail)
        //调用地址解析接口
        Map.geocoder({
          //获取表单传入地址
          address: address.AddressDetail, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
          success: (res) => { //成功后的回调
            resolve(res);
          },
          fail: (res) => { // 失败后的回调
            // console.log(123123123)
            reject(res);
          }
        });
      });

      PromiseId.then((res) => {
          // console.log(res);
          address.lat = res.result.location.lat; // 纬度
          address.lng = res.result.location.lng; // 经度
          new Request('update_order_address_info.cls.php').request(
            () => {
              return {
                order_id: this.orderid,
                openid: app.globalData.openid,
                address: JSON.stringify(address),
              }
            },
            (res) => {
				console.log(address)
				if(res.data.code == 1){
					_this.data.address[0].name = address.name0
					_this.data.address[0].phone = address.phone0
					_this.data.address[0].addname = address.AddressDetail
					_this.setData({
						address:_this.data.address
					})
				}
              res.data.code == 1 ? Requ.showToast('修改地址成功') : Requ.showToast('修改地址失败');
            }
          );
        },
        (res) => {
          Requ.showToast('地址输入有误', 'error');
        });


    });
  },
  toShopping:function(){
	wx.switchTab({
		url:"/pages/shoplist/shoplist"
	})  
  },
  //获取购物车列表
  GetShopCarList: function(){
    wx.request({
      url: HostUrl.SZXURL + HostUrl.CartList,
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'openid': app.globalData.openid,
      },
      success: (res) => {
		  console.log(res)
        let respone = res.data;
        if(respone.data.data == 0){
          Requ.showToast('购物车列表为空', 'none', ()=>{
            setTimeout(function () {
              wx.navigateBack({
                delta: 1,
              });
          }, 2000);
          });
          return;
        }
        for(let key in respone['data']['data']){
          respone['data']['data'][key]['image'] = HostUrl.HostName + respone['data']['data'][key]['image'];
        };
        // res.data.data.data.map((e)=>{
        //   e.image = HostUrl.HostName + e.image;
        // });
        this.setData({
          ShopList: respone['data'],
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onLoad: function () {
	// 获取用户地址
	new Request('get_user_addresslist.cls.php').request(
	    () => {
	      return {
	        data: 1,
	        openid: app.globalData.openid,
	      }
	    },
	    (res) => {
			console.log(res)
	        if(res.data.address == undefined){
	            Requ.showToast('暂无地址信息');
	            return;
	        }
	        this.setData({
	            address: res.data.address
	        })
	    }
	);
  },
    /**
   * 
   * @param {计算两个经纬度的距离 km} e 
   */
  getaddreskm:function(lat1, lng1, lat2, lng2){
    var radLat1 = lat1*Math.PI / 180.0;
    var radLat2 = lat2*Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
    s = s *6378.137 ;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    return s;
  
    
  },
  createOrder:function(){
	  let _this = this
	  let goodsList = Array.from(app.globalData.shopCart)
	  let length = goodsList.length
	  for(let i =0;i<length;i++){
		  let len = goodsList[i].data.length
		  for(let j=0;j<len;j++){
			  if(goodsList[i].data[j].active==false){
				  goodsList[i].optionalnum-=goodsList[i].data[j].num
				  goodsList[i].data.splice(j,1)
				  j--
				  len--
			  }
		  }
		  if(goodsList[i].optionalnum==0){
			  goodsList.splice(i,1)
			  i--
			  length--
		  }
	  }
	  console.log(goodsList)
	  console.log(app.globalData.shopCart)
	  if(goodsList.length==0){
		  wx.showToast({
		  	title: '请选择商品',
		  	icon: 'none',
		  	duration: 2000
		  })
		  return
	  }
	new Request('create_order.cls.php').request(
	  () => {
	    return {
	      goods: JSON.stringify(goodsList),
	      /* self_site_id: 47, */
			openid: getApp().globalData.openid,
			self_site_id: getApp().globalData.self_site_id,
	    }
	  },
	  (res) => {
		  console.log(res)
	  		getApp().globalData.orderid = res.data.orderid
	  		wx.navigateTo({
				url:'/pages/pay/pay'
			})
	});
  },
  del:function(e){
	  console.log(this.data.shopCart)
	  console.log(e)
	  let shop = this.data.shopCart[e.target.dataset.shopindex]
	  let good = this.data.shopCart[e.target.dataset.shopindex].data[e.target.dataset.goodindex]
	  console.log(shop)
	  console.log(good)
	  good.num-=1
	  good.groupprice=Number(good.groupprice)
	  good.addprice=Number(good.addprice)
	  shop.addprice=Number(shop.addprice)
	  this.data.totalPrice=Number(this.data.totalPrice)
	  good.groupprice-=good.addprice
	  shop.optionalnum-=1
	  shop.addprice-=good.addprice
	  this.data.totalPrice-=good.addprice
	  good.groupprice = good.groupprice.toFixed(2)
	  shop.addprice = shop.addprice.toFixed(2)
	  this.data.totalPrice = this.data.totalPrice.toFixed(2)
	  if(good.num==0){
	  		shop.data.splice(e.target.dataset.goodindex,1)
	  }
	  if(shop.optionalnum==0){
		  this.data.shopCart.splice(e.target.dataset.shopindex,1)
	  }
	  this.setData({
		  shopCart:this.data.shopCart,
		  totalPrice:this.data.totalPrice
	  })
	  console.log(this.data.shopCart)
  },
  add:function(e){
	  console.log(this.data.shopCart)
	  console.log(e)
	  let shop = this.data.shopCart[e.target.dataset.shopindex]
	  let good = this.data.shopCart[e.target.dataset.shopindex].data[e.target.dataset.goodindex]
	  console.log(shop)
	  console.log(good)
	  good.groupprice=Number(good.groupprice)
	  good.addprice=Number(good.addprice)
	  shop.addprice=Number(shop.addprice)
	  this.data.totalPrice=Number(this.data.totalPrice)
	  good.num+=1
	  good.groupprice+=good.addprice
	  shop.optionalnum+=1
	  shop.addprice+=good.addprice
	  this.data.totalPrice+=good.addprice
	  good.groupprice = good.groupprice.toFixed(2)
	  shop.addprice = shop.addprice.toFixed(2)
	  this.data.totalPrice = this.data.totalPrice.toFixed(2)
	  this.setData({
	  		  shopCart:this.data.shopCart,
			  totalPrice:this.data.totalPrice
	  })
	  console.log(this.data.shopCart)
  },
  activeGood:function(e){
	  console.log(this.data.shopCart)
	  console.log(e)
	  let shop = this.data.shopCart[e.target.dataset.shopindex]
	  let good = this.data.shopCart[e.target.dataset.shopindex].data[e.target.dataset.goodindex]
	  console.log(shop)
	  console.log(good)
	  good.groupprice=Number(good.groupprice)
	  good.addprice=Number(good.addprice)
	  shop.addprice=Number(shop.addprice)
	  this.data.totalPrice=Number(this.data.totalPrice)
	  good.active = !good.active
	  if(good.active==true){
		  shop.addprice+=good.groupprice
		  this.data.totalPrice+=good.groupprice
	  }else{
		  shop.addprice-=good.groupprice
		  this.data.totalPrice-=good.groupprice
	  }
	  shop.addprice=shop.addprice.toFixed(2)
	  this.data.totalPrice=this.data.totalPrice.toFixed(2)
	  this.setData({
	  		  shopCart:this.data.shopCart,
			  totalPrice:this.data.totalPrice
	  })
	  console.log(this.data.shopCart)
  }
})